package com.sx.manage.controller.consumer;

import java.io.IOException;
import java.text.ParseException;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.sx.common.util.NumberUtil;
import com.sx.common.util.StringUtil;
import com.sx.common.util.ValidateUtil;
import com.sx.common.util.json.JackJsonUtil;
import com.sx.manage.biz.consumer.IMCompanyConsumerInfoBiz;
import com.sx.manage.controller.base.MBaseController;
import com.sx.manage.service.consumer.IMBaseCompanyConsumerInfoService;
import com.sx.manage.servlet.ViewAndModel;
import com.sx.manage.util.ExcelUtils;
import com.sx.manage.util.PropertiesUtils;
import com.sx.model.constants.MDataStatusType;
import com.sx.model.constants.MSystemConstants;
import com.sx.model.manage.mybatis.form.consumer.MCompanyConsumerInfoForm;
import com.sx.model.manage.mybatis.vo.consumer.company.MComConsumerVO;
import com.sx.model.manage.mybatis.vo.importerror.MImpExcelErrorVO;
import com.sx.model.manage.mybatis.vo.result.ResultBooleanVO;
import com.sx.model.manage.mybatis.vo.result.ResultExcelVO;
import com.sx.model.manage.mybatis.vo.result.ResultListVO;
import com.sx.model.manage.mybatis.vo.result.ResultObjectVO;
import com.sx.model.util.StringsUtil;

/**
 * 公司用户
 * 
 * @author zwm
 *
 */
@Controller
@RequestMapping("/companyconsumer")
public class MConsumerCompanyController extends MBaseController {

	private Logger log = LoggerFactory.getLogger(this.getClass());

	@Resource(name = "mCompanyConsumerInfoBizImpl")
	private IMCompanyConsumerInfoBiz mCompanyConsumerInfoBizImpl;

	@Resource(name = "mBaseCompanyConsumerInfoServiceImpl")
	private IMBaseCompanyConsumerInfoService mBaseCompanyConsumerInfoServiceImpl;

	/**
	 * 添加页面跳转
	 * 
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping(value = "company_consumer_add_view")
	public ViewAndModel add_view_company_consumer() {
		ViewAndModel viewAndModel = new ViewAndModel(request, cache);
		String userCode = StringsUtil.uniqueCode(MSystemConstants.CONSUMER_PREFIX_COMPANY);
		MComConsumerVO companyUserVO = new MComConsumerVO();
		companyUserVO.setConsumer_code(userCode);
		viewAndModel.addObject("userVO", companyUserVO);
		viewAndModel.setViewName("users/company/addCompanyUser");// 跳转页面设置
		return viewAndModel;
	}

	/**
	 * 公司管理用户添加
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping("company_consumer_adds")
	@ResponseBody
	public ResultObjectVO<MComConsumerVO> add(MCompanyConsumerInfoForm form) {
		if (StringUtils.isNotBlank(form.getEmail()) && !ValidateUtil.isEmail(form.getEmail())) {
			log.info("邮箱格式错误email={}",form.getEmail());
			return new ResultObjectVO<>(false, null, "邮箱格式错误");
		}
		if (null != form.getId()) {
			log.info("公司用户信息编辑form={}",form);
			return mCompanyConsumerInfoBizImpl.update_companyConsumer(form, loginConsumer());
		}
		log.info("公司用户信息新增form={}",form);
	    return mCompanyConsumerInfoBizImpl.save_compyConsumer(form, loginConsumer());
	}

	/**
	 * 添加页面跳转
	 * 
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping(value = "query_company_consumer_view")
	public ViewAndModel query_view_company_consumer() {
		ViewAndModel viewAndModel = new ViewAndModel(request, cache);
		viewAndModel.setViewName("users/company/companyUser");// 跳转页面设置
		viewAndModel.addObject("current", "comUser");// 界面展开 菜单栏使用
		return viewAndModel;
	}

	/**
	 * 查询公司用户列表数据
	 * 
	 * @param form
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping(value = "query_company_consumer")
	@ResponseBody
	public ResultListVO<MComConsumerVO> query_company_user_list(MCompanyConsumerInfoForm form) {
		log.info("查询公司用户列表form={}",form);
		return mBaseCompanyConsumerInfoServiceImpl.get_consumer_page(form);
	}

	/**
	 * 查询公司用户
	 * 
	 * @param form
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 * @throws ParseException
	 */
	@RequestMapping("/update_view_company_consumer/{id}")
	@ResponseBody
	public ViewAndModel update_view_company_consumer(MCompanyConsumerInfoForm form) {
		ViewAndModel viewAndModel = new ViewAndModel(request, cache);
		ResultObjectVO<MComConsumerVO> result = mBaseCompanyConsumerInfoServiceImpl.get_companyConsumer_byId(form.getId());
		viewAndModel.addObject("mComConsumerVO", result.getObjVo());
		viewAndModel.setViewName("users/company/editCompanyUser");// 修改ftl页面名称
		return viewAndModel;
	}

	@RequestMapping("/query_company_consumer_role")
	@ResponseBody
	public ResultBooleanVO query_company_consumer_role(HttpServletRequest request, HttpServletResponse response) {
		Long userId = Long.valueOf(request.getParameter("id"));
		String companyIds = request.getParameter("comId");
		if (null == userId) {
			return null;
		}
		Long[] companyId = StringUtil.StringtoLong2(companyIds);
		log.info("查询公司用户角色userId={},companyId={}",userId,companyId);
		return mCompanyConsumerInfoBizImpl.query_consumerRelations(companyId, userId, loginConsumer());
	}

	/**
	 * 更改用户状态-停用-启用
	 * 
	 * @param userIds
	 * @param data_status
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping("/update_company_consumer_status")
	@ResponseBody
	public ResultBooleanVO update_status_company_consumer(Long[] userIds, Long id, HttpServletRequest request, HttpServletResponse response) {
		String data_status = request.getParameter("data_status");
		if (null == data_status) {
			return new ResultBooleanVO("sj.m.data.status.error");
		}
		ResultBooleanVO ResultVO = new ResultBooleanVO();
		log.info("修改公司用户状态data_status={},userIds={},id={}",data_status,NumberUtil.arrayToStr(userIds),id);
		if (null != userIds) {
			if (data_status.equals(MDataStatusType.DATA_DISABLE.toString())) {
				// 停用
				ResultVO = mCompanyConsumerInfoBizImpl.consumersDisable(userIds, loginConsumer());
			} else {
				ResultVO = mCompanyConsumerInfoBizImpl.consumersEnable(userIds, loginConsumer());
			}
		}
		if (null != id) {
			if (data_status.equals(MDataStatusType.DATA_DISABLE.toString())) {
				// 停用
				ResultVO = mCompanyConsumerInfoBizImpl.consumersOneDisable(id, loginConsumer());
			} else {
				ResultVO = mCompanyConsumerInfoBizImpl.consumersOneEnable(id, loginConsumer());
			}

		}
		return ResultVO;

	}

	/**
	 * 重置密码
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping("/reset_company_consumer_password")
	@ResponseBody
	public ResultBooleanVO resetPassWord(HttpServletRequest request, HttpServletResponse response) {
		String requestMessage = extract_param_from_request(request);
		Map map = JackJsonUtil.jsonToMap(requestMessage, String.class, String.class);
		Long id = Long.valueOf(map.get("id").toString());
		if (null == id || 0 == id) {
			return new ResultBooleanVO("sj.m.password.parameter.error");
		}
		log.info("重置公司用户密码id={}",id);
		return mCompanyConsumerInfoBizImpl.resetConsumerPassword(id, null, loginConsumer());
	}

	/**
	 * 导入公司用户
	 * 
	 * @param file
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping("/import_company_consumer")
	@ResponseBody
	public ResultListVO importUser(@RequestParam(value = "files", required = false) MultipartFile file) {
		if (null == file) {
			return new ResultListVO(false, "文件错误", null);
		}
		String fileName = file.getOriginalFilename();
		log.info(" 公司用户=====导入文件名称为:" + fileName);
		String prefix = fileName.substring(fileName.lastIndexOf(".") + 1);
		if (!"xlsx".equals(prefix)) {
			return new ResultListVO(false, "只支持2007版Excel!", null);
		}
		List<Map<String, String>> listMap = PropertiesUtils.proToMaps(MSystemConstants.PERSONAL_COMPANY_IMPORT_FILE_PATH);
		ResultExcelVO<?> results = ExcelUtils.fileToExcel(file, listMap.get(0), listMap.get(1));
		if (!results.isSuccess()) {
			ResultListVO<MImpExcelErrorVO> result = new ResultListVO<>(false, null, results.getMsg());
			result.setData(null);
			return result;
		}
		return this.mCompanyConsumerInfoBizImpl.consumerExcelImport(results.getListMap(), loginConsumer());
	}

}
